# -*- coding: utf-8 -*-
"""
Created on Wed May 12 15:20:56 2021

@author: Apple
"""
import sympy as sp
import math
import numpy as np
import pandas as pd
import os
import sys

class Logger(object):
    def __init__(self, filename="Default.log"):
        self.terminal = sys.stdout
        self.log = open(filename, "a")
 
    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)
 
    def flush(self):
        pass

def calvalue(x): # 函数值计算
    y = x-math.cos(x)
    return y

def dichotomy(a:float,b:float,c:float): # 二分法近似求解根
    x = (a+b)/2
    fx = calvalue(x)
    K = []
    
    while abs(fx)>=c:
        k = []
        k.append(a)
        k.append(b)
        x = (a+b)/2
        k.append(x)
        fx = calvalue(x)
        k.append(fx)
        if fx>0:
            b = x
        elif fx<0:
            a = x
        else:
            K.append(k)
            break

        K.append(k)
    return K

def main(a,b,c):
    
    type = sys.getfilesystemencoding()
    sys.stdout = Logger('scheme2.txt')
    
    x = sp.symbols('x')
    y = x-sp.cos(x)
    
    print('函数表达式为: f(x) =',y)
    print('区间下界为%.2f,区间上界为%.2f'%(a,b))
    K = dichotomy(a,b,c)
    # print(K)
    
    df = pd.DataFrame(K,columns=["ak", 'bk',"xk", "f(xk)"])
    
    print(f'计算精度为{c}')
    print(f'经过{len(K)}次迭代后，xk的值为{K[-1][2]}，此时f(xk)={K[-1][3]}')
    print('二分法求解结果如下：')
    print(df)

if __name__=="__main__":
    a = 0 # 初始参数设置
    b = 1
    c = 0.001
    main(a,b,c)
        